﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Windows;
using System.Windows.Browser;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace Control.UI.Voice
{
    public class TranslationDownloader
    {
        public static readonly TranslationDownloader Instance = new TranslationDownloader();

        private TranslationDownloader()
        {
        }

        private readonly object _lock = new object();

        private readonly IDictionary<string, byte[]> _cachedTranslations = new Dictionary<string, byte[]>();

        public void Download(string speech)
        {
            Download(speech, null);
        }

        public void Download(string speech, Action<byte[]> callback)
        {
            lock (_lock)
            {
                byte[] transation;
                if (_cachedTranslations.TryGetValue(speech, out transation))
                {
                    if (callback != null)
                        callback(transation);

                    return;
                }
            }

            string appId = "6BE113C8CDA4C822A81747F980F0DC7DFBD57428";//go to http://msdn.microsoft.com/en-us/library/ff512386.aspx to obtain AppId.
            string language = "en";

            string uri = "http://api.microsofttranslator.com/v2/Http.svc/Speak?appId=" + appId + "&text=" + HttpUtility.UrlEncode(speech) + "&language=" + language;
            //string uri = "http://api.ispeech.org/api/rest?apikey=e62d72bf6906257e8136eef8b86ef50c&action=convert&text=" + HttpUtility.UrlEncode(speech);
            HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(uri);

            httpWebRequest.BeginGetResponse(new AsyncCallback((r) =>
            {
                MemoryStream ms = new MemoryStream();

                using (WebResponse response1 = httpWebRequest.EndGetResponse(r))
                using (Stream s = response1.GetResponseStream())
                {
                    s.CopyTo(ms);
                }

                byte[] data = ms.ToArray();

                _cachedTranslations[speech] = data;

                if (callback != null)
                    callback(data);
            }), null);

        }
    }
}